import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import { HttpService } from '@nestjs/axios';
import WorkException from 'exception/work.exception';
import { createHash, randomUUID } from 'crypto';
import { UpdateInfoDto } from './dto/update.info.dto';
import { ImclientService } from '@app/imclient';
import { User } from '@app/db/entity/User';

@Injectable()
export class UserService {
    private readonly prefix = 'user:';

    constructor(
        private readonly db:DbService,
        //private readonly cache:CacheService,
        private readonly http:HttpService,
        private readonly imclient:ImclientService,
    ) {}

    checkPwdFormat(pwd:string) {
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
        if(!regex.test(pwd)) {
            throw new WorkException('新密码必须同时包含大小写字母和数字，且不少于8位')
        }
    }

    async updateBaseInfo(info:User, userId:number) {
        if(Object.keys(info).length == 0) return true

        this.db.user.update({id: userId}, info)

        return true
    }


    generateSalt() {
        return randomUUID().split('-').pop().toLocaleLowerCase()
    }

    buildPassword(password:string, salt:string) {
        password = createHash('sha256').update(password + salt).digest('hex').toLowerCase()
        return createHash('sha256').update(password + salt).digest('hex').toLowerCase()
    }

    async changePwd(userId:number, oldpwd:string, newpwd:string) {
    
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
        
        if(!regex.test(newpwd)) {
            throw new WorkException('新密码必须同时包含大小写字母和数字，且不少于8位')
        }


        const member = await this.db.user.findOne({id : userId}, ['password', 'salt'])
        if(this.buildPassword(oldpwd, member.salt) != member.password) throw new WorkException('旧密码错误')
        if(newpwd == oldpwd) throw new WorkException('新密码不能和旧密码一样')

        member.salt = this.generateSalt()
        member.password = this.buildPassword(newpwd, member.salt)
        
        return this.db.user.update({id : userId}, member)
        
    }

    async setPassword(userId:number, password:string) {
        this.checkPwdFormat(password)

        const salt = this.generateSalt()
        password = this.buildPassword(password, salt)

        const r = await this.db.user.update({id: userId}, {password: password, salt: salt})

        return r == 1
    }


  

    
}
